import logging
from tool_class.db_connection import get_connection
import json
import re

log = logging.getLogger(__name__)


def get_data(client_name, db_type, sql):
    """
    获取数据库数据
    """
    conn = get_connection(client_name, db_type)
    with conn.cursor() as cursor:  # cursor 对象允许你执行SQL语句并获取结果  ，使用with后自动关闭游标
        # 使用cursor.execute()执行一个SQL查询语句
        cursor.execute(sql)
        result_set_tuple = cursor.fetchall()  # 使用 cursor.fetchall() 获取查询结果返回字典类型 fetchall() 方法返回一个元组列表
    conn.close()
    return result_set_tuple


def test_check_data_001():
    """
    数据校验
    """
    rule_name = "前置-文本-内容包含380四驱豪过滤"
    client_name = "富通东方"

    rule_detail_list = get_rule_data(client_name, rule_name)

    processed_data(client_name, rule_detail_list)


def test_check_data_002():
    """
    数据校验
    """
    # 条件:车系名称为哈弗
    rule_name = "后置规则-品牌名称修改为哈弗品牌"
    client_name = "富通东方"
    rule_detail_list = get_rule_data(client_name, rule_name)
    print("规则内容：", rule_detail_list)
    processed_data(client_name, rule_detail_list)


def test_check_data_003():
    """
    数据校验
    """
    # 条件：原文片段内容包含正则：.*弗H6.*
    rule_name = "后置规则-车系名称修改为哈弗H9"
    client_name = "富通东方"
    rule_detail_list = get_rule_data(client_name, rule_name)  # 获取规则数据
    print("规则内容：", rule_detail_list)
    processed_data(client_name, rule_detail_list)


def get_rule_data(client_name, rule_name):
    """
    获取规则数据
    """

    sql = f"select * from ins_regulation_info where `name` = '{rule_name}'"
    result_set_tuple = get_data(client_name, 'rule_query', sql)
    # print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', result_set_tuple)
    log.info(f">>>>>>{result_set_tuple}")
    # 获取列表中第一个字典的id值
    first_item = result_set_tuple[0] if result_set_tuple else None
    rule_id = first_item["id"]  # 规则id
    process_phase = first_item["process_phase"]  # 规则阶段、前置处理:pre 后置处理:post
    regulation_type = first_item["regulation_type"]  # 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
    content_type = first_item["content_type"]  # 规则内容类型（text：文本、order：工单）
    channel = first_item["channel"]  # 数据渠道
    print("规则表规则id是:", rule_id)
    print("规则阶段是:", process_phase)
    print("规则表规则类型是:", regulation_type)
    print("规则表规则内容类型是:", content_type)
    print("规则表数据渠道是:", channel)
    if rule_id:
        # 获取规则详情数据，数据库有一条或两条数据，一条是条件detail_type为0，一条是执行detail_type为1
        sql = f"select * from ins_regulation_detail where regulation_id = '{rule_id}'"
        rule_details = get_data(client_name, 'rule_query', sql)
        # # 获取数据长度
        # rule_details_length = len(rule_details)
        # 初始化一个空列表来存储所有的规则详情集合
        rule_detail_list = []
        if rule_details:
            for itme in rule_details:
                rule_detail_dictionary = {'regulation_id': itme.get('regulation_id'),
                                          'process_phase': process_phase,
                                          'regulation_type': regulation_type,
                                          'content_type': content_type,
                                          'channel': channel,
                                          'field_name': itme.get('field_name'),
                                          'variable_value': itme.get('variable_value'),
                                          'logical_operator': itme.get('logical_operator'),
                                          'condition_type': itme.get('condition_type'),
                                          'condition_detail': itme.get('condition_detail'),
                                          'detail_type': itme.get('detail_type'),
                                          'names': get_resource_group_content(client_name, itme.get('condition_type'),
                                                                              itme.get('condition_detail'))}
                rule_detail_list.append(rule_detail_dictionary)
        # 规则详情表规则id regulation_id
        # process_phase  规则阶段、前置处理:pre 后置处理:post
        # detail_type 规则条件：0 规则执行：1
        # regulation_type 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
        # field_name 字段名称
        # variable_value 变量值
        # logical_operator 逻辑运算符（contain：包含、notContain：不包含、empty：为空、notEmpty：不为空、equals：==、notEqual：!=）
        # condition_type 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
        # condition_detail 条件详情 、只有资源组时值为id，其他为条件的值
        # names 资源组内容详情, condition_type类型为resourceGroup资源组时才会用到names
        # 按照 'detail_type' 大小进行排序
        # 使用 sorted 函数和 lambda 表达式来指定排序的关键字
        sorted_rule_detail_list = sorted(rule_detail_list, key=lambda x: int(x['detail_type']))
        return sorted_rule_detail_list


def get_resource_group_content(client_name, condition_type, condition_detail):
    """
    获取资源组内容
    """
    names = []  # 用于保存资源组中详情字段为name
    if condition_type == 'resourceGroup':
        if condition_detail:
            sql = f"select * from ins_data_resource_desc where resource_id = '{condition_detail}' and status != 'Disabled'"
            condition_details = get_data(client_name, 'rule_query', sql)  # 资源组详情
            # print("【condition_details】", condition_details)
            if condition_details:
                # 遍历列表中的每个字典
                for item in condition_details:
                    # 获取当前字典中name的值，并将其添加到names列表中
                    name = item.get('name')
                    if name is not None:  # 确保name不是None
                        names.append(name)
            print("names:", names)
    return names


def raw_data(client_name, logical_operator, condition_detail, field_name, new_id_array, content_type, channel):
    if client_name == '安徽大众':
        client_id = 'f25f2b8837e10c6ea50cb2c5f1e7aa48'
    if client_name == '富通东方':
        client_id = '1'
    # process_phase  规则阶段、前置处理:pre 后置处理:post
    # detail_type 规则条件：0 规则执行：1
    # regulation_type 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
    # field_name 字段名称
    # variable_value 变量值
    # logical_operator 逻辑运算符（contain：包含、notContain：不包含、empty：为空、notEmpty：不为空、equals：==、notEqual：!=）
    # condition_type 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
    # condition_detail 条件详情 、只有资源组时值为id，其他为条件的值
    # content_type  规则内容类型（text：文本、order：工单）
    # channel 渠道，渠道id
    # names 资源组内容详情, condition_type类型为resourceGroup资源组时才会用到names
    # new_id_array 已处理并验证通过的数据id
    """
    获取前置规则原始数据
    """
    i = 0
    sql = f"SELECT * FROM ays_meta_data_analysis where `content_type`='{content_type}' and `channel_id` in {channel} and `client_id`='{client_id}'"
    raw_data_content = get_data(client_name, 'data_query', sql)
    # print("【raw_data_content】", raw_data_content)
    print("aaaaaaaaaaaaaaaaaaaaaaaa", new_id_array)
    if raw_data_content:
        for item in raw_data_content:
            if item.get('new_id') not in new_id_array:
                data_content = item.get('data')  # 获取每条数据中data字段的数据内容
                if data_content is not None:
                    # 使用json.loads()函数将JSON字符串转换为Python字典
                    data_content = json.loads(data_content)
                    field_name_content = data_content.get(field_name)  # 获取每条数据中data字段中field_name字段的值
                    if logical_operator == 'contain':
                        # 检查字符串是否包含另一个字符串
                        condition = condition_detail in field_name_content
                    elif logical_operator == 'equals':
                        # 检查两个字符串是否相等
                        condition = field_name_content == condition_detail
                    elif logical_operator == 'empty':
                        # 检查字符串是否为空
                        condition = field_name_content == ''
                    elif logical_operator == 'notEmpty':
                        # 检查字符串是否非空
                        condition = field_name_content != ''
                    elif logical_operator == 'notEquals':
                        # 检查两个字符串是否不相等
                        condition = condition_detail != field_name_content
                    elif logical_operator == 'notContain':
                        # 检查字符串是否不包含另一个字符串
                        condition = condition_detail not in field_name_content

                    if condition:
                        print("过滤不符合条件数据id为", item.get('new_id'))
                        return False
                    else:
                        print("包含,过滤符合条件数据id为", item.get('new_id'))
                        print(f"{field_name}字段的值为", field_name_content)
                        i = 1 + i
                        print('!!!!!!!!!!!!!', i)

    return True


def post_raw_data(client_name, logical_operator, condition_detail, field_name, new_id_array, content_type, channel):
    if client_name == '安徽大众':
        client_id = 'f25f2b8837e10c6ea50cb2c5f1e7aa48'
    if client_name == '富通东方':
        client_id = '1'
    # process_phase  规则阶段、前置处理:pre 后置处理:post
    # detail_type 规则条件：0 规则执行：1
    # regulation_type 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
    # field_name 字段名称
    # variable_value 变量值
    # logical_operator 逻辑运算符（contain：包含、notContain：不包含、empty：为空、notEmpty：不为空、equals：==、notEqual：!=）
    # condition_type 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
    # condition_detail 条件详情 、只有资源组时值为id，其他为条件的值
    # content_type  规则内容类型（text：文本、order：工单）
    # channel 渠道，渠道id
    # names 资源组内容详情, condition_type类型为resourceGroup资源组时才会用到names
    # new_id_array 已处理并验证通过的数据id
    """
    后置规则处理前原始数据
    """
    i = 0
    sql = f"SELECT * FROM ays_api_reslt_data_analysis where `content_type`='{content_type}' and `channel_id` in {channel} and `client_id`='{client_id}'"
    raw_data_content = get_data(client_name, 'data_query', sql)
    # print("【raw_data_content】", raw_data_content)
    print("aaaaaaaaaaaaaaaaaaaaaaaa", new_id_array)
    if raw_data_content:
        for item in raw_data_content:
            if item.get('new_id') not in new_id_array:
                field_name_content = item.get(field_name)  # 获取每条数据中data字段中field_name字段的值
                if field_name_content is not None:
                    if logical_operator == 'contain':
                        # 检查字符串是否包含另一个字符串
                        condition = condition_detail in field_name_content
                    elif logical_operator == 'equals':
                        # 检查两个字符串是否相等
                        condition = field_name_content == condition_detail
                    elif logical_operator == 'empty':
                        # 检查字符串是否为空
                        condition = field_name_content == ''
                    elif logical_operator == 'notEmpty':
                        # 检查字符串是否非空
                        condition = field_name_content != ''
                    elif logical_operator == 'notEquals':
                        # 检查两个字符串是否不相等
                        condition = condition_detail != field_name_content
                    elif logical_operator == 'notContain':
                        # 检查字符串是否不包含另一个字符串
                        condition = condition_detail not in field_name_content

                    if condition:
                        print("过滤不符合条件数据id为", item.get('new_id'))
                        return False
                    else:
                        print("包含,过滤符合条件数据id为", item.get('new_id'))
                        print(f"{field_name}字段的值为", field_name_content)
                        i = 1 + i
                        print('!!!!!!!!!!!!!', i)

    return True


def before_processing_raw_data(client_name, rule_detail):
    if client_name == '安徽大众':
        client_id = 'f25f2b8837e10c6ea50cb2c5f1e7aa48'
    if client_name == '富通东方':
        client_id = '1'
    """
    后置规则处理前原始数据
    """
    # process_phase  规则阶段、前置处理:pre 后置处理:post
    # detail_type 规则条件：0 规则执行：1
    # regulation_type 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
    # field_name 字段名称
    # variable_value 变量值
    # logical_operator 逻辑运算符（contain：包含、notContain：不包含、empty：为空、notEmpty：不为空、equals：==、notEqual：!=）
    # condition_type 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
    # condition_detail 条件详情 、只有资源组时值为id，其他为条件的值
    # names 资源组内容详情, condition_type类型为resourceGroup资源组时才会用到names
    # content_type  规则内容类型（text：文本、order：工单）
    # channel 渠道，渠道id
    # before_processing_raw_id 符合条件后置规则处理前原始数据id
    before_processing_raw_id = []

    field_name = rule_detail.get('field_name')  # 字段名称
    condition_detail = rule_detail.get('condition_detail')  # 条件详情:只有资源组时值为id，其他为条件的值
    logical_operator = rule_detail.get('logical_operator')  # 逻辑运算符（contain：包含、notContain：不包含、empty：为空、notEmpty
    # ：不为空、equals：==、notEqual：!=）
    condition_type = rule_detail.get('condition_type')  # 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
    content_type = rule_detail.get('content_type')  # 规则内容类型（text：文本、order：工单）
    names = rule_detail.get('names')  # 资源组内容详情
    channel = rule_detail.get('channel')  # 渠道，渠道id
    channel = channel.replace('[', '(').replace(']', ')')

    base_sql = f"select * from ays_api_reslt_data_analysis where `content_type`='{content_type}' and `channel_id` in {channel} and `client_id`='{client_id}'"
    # 初始化sql_operator变量
    sql_operator = ''
    # 根据logical_operator设置sql_operator
    if logical_operator == 'equals':
        sql_operator = '='
    elif logical_operator == 'contain':
        sql_operator = 'LIKE'
    elif logical_operator == 'empty':
        sql_operator = 'IS NULL'
    elif logical_operator == 'notEmpty':
        sql_operator = 'IS NOT NULL'
    elif logical_operator == 'notEqual':
        sql_operator = '!='
    elif logical_operator == 'notContain':
        sql_operator = 'NOT LIKE'

    if condition_type == 'value':
        # 根据sql_operator构建SQL语句
        sql = f"{base_sql} and `{field_name}` {sql_operator} '%{condition_detail}%'"
        if logical_operator == 'equals' or logical_operator == 'not_equals':  # 对于'equals'，不需要%前后缀
            sql = sql.replace('%', '')
        if logical_operator == 'empty' or logical_operator == 'not_empty':
            sql = f"{base_sql} and `{field_name}` {sql_operator}"
    else:
        sql = 'sql语句为空'

    if condition_type == 'regex':
        if logical_operator == 'contain':
            sql_operator = 'regexp'
            sql = f"{base_sql} and `{field_name}` {sql_operator} '{condition_detail}'"
        if logical_operator == 'notContain' or logical_operator == 'not_equals':
            sql_operator = 'not regexp'
            sql = f"{base_sql} and `{field_name}` {sql_operator} '{condition_detail}'"

    if condition_type == 'resourceGroup':
        print("资源组具体值：", names)
        # 根据sql_operator构建SQL语句
        if logical_operator == 'contain':
            splicing = 'LIKE'
        if logical_operator == 'notContain':
            splicing = 'NOT LIKE'
        if logical_operator == 'contain' or logical_operator == 'notContain':
            like_clauses = []
            resourceGroup_sql = ''
            for names_content in names:
                like_clauses.append(f"`{field_name}` {splicing} '%{names_content}%'")
            # 将所有的 LIKE 子句用 OR 连接起来
            if logical_operator == 'contain':
                resourceGroup_sql += " OR ".join(like_clauses)
            if logical_operator == 'notContain':
                resourceGroup_sql += " AND ".join(like_clauses)
            sql = f"{base_sql} and ({resourceGroup_sql})"

        names = tuple(names)
        if logical_operator == 'equals':
            sql = f"{base_sql} and `{field_name}` in {names}"
        if logical_operator == 'notEqual':
            sql = f"{base_sql} and `{field_name}` not in {names}"

    print("【sql】", sql)
    raw_data_content = get_data(client_name, 'data_query', sql)
    # print("【raw_data_content】", raw_data_content)
    if raw_data_content:
        for item in raw_data_content:
            before_processing_raw_id.append(item.get('new_id'))
    return before_processing_raw_id


def processed_data(client_name, rule_detail_list):
    if client_name == '安徽大众':
        client_id = 'f25f2b8837e10c6ea50cb2c5f1e7aa48'
    if client_name == '富通东方':
        client_id = '1'
    # 初始化一个空列表来存储所有的规则详情集合
    # rule_detail_list = []
    # rule_id 规则id
    # detail_type 规则条件：0 规则执行：1
    # process_phase  规则阶段、前置处理:pre 后置处理:post
    # regulation_type 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
    # field_name 字段名称
    # variable_value 变量值
    # logical_operator 逻辑运算符（contain：包含、notContain：不包含、empty：为空、notEmpty：不为空、equals：==、notEqual：!=）
    # condition_type 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
    # condition_detail 条件详情 、只有资源组时值为id，其他为条件的值
    # content_type  规则内容类型（text：文本、order：工单）
    # channel 渠道，渠道id
    # names 资源组内容详情, condition_type类型为resourceGroup资源组时才会用到names
    """
    获取已处理数据
    """
    eligible_data = []  # 从后置规则原始表中查出，符合条件已处理数据
    new_id_array = []  # 用于保存已处理并验证通过的前置处理数据id，查询前置规则的原始数据
    failure_processed = True  # 默认为True，表示所有规则都执行成功
    failure_raw = True  # 默认为True，前置规则原始数据表所有数据校验的结果
    sql = ''
    for rule_detail in rule_detail_list:
        rule_id = rule_detail.get('regulation_id')  # 规则id
        field_name = rule_detail.get('field_name')  # 字段名称
        logical_operator = rule_detail.get('logical_operator')  # 逻辑运算符
        condition_detail = rule_detail.get('condition_detail')  # 条件详情 、只有资源组时值为id，其他为条件的值
        detail_type = rule_detail.get('detail_type')  # 条件类型：规则条件：0 规则执行：1
        regulation_type = rule_detail.get('regulation_type')  # 规则类型（R01：修改、R02：脱敏、R03：补充、R04：清洗、R05：过滤）
        process_phase = rule_detail.get('process_phase')  # 规则阶段、前置处理:pre 后置处理:post
        condition_type = rule_detail.get('condition_type')  # 条件类型（resourceGroup：资源组、value：值、regex：正则表达式）
        content_type = rule_detail.get('content_type')  # 规则内容类型（text：文本、order：工单）
        names = rule_detail.get('names')  # 资源组内容详情
        channel = rule_detail.get('channel')  # 渠道，渠道id
        channel = channel.replace('[', '(').replace(']', ')')

        if regulation_type == 'R05':  # R05：过滤
            abandon = '1'  # abandon='1'表示已执行过滤，'0'表示未过滤
        if regulation_type == 'R01' or regulation_type == 'R03':  # R01：修改 R03：补充
            done = '1'  # done='1'表示已执行处理，'0'表示未处理
        if process_phase == 'pre':  # process_phase规则阶段、前置处理:pre 后置处理:post
            sql = f"select * from ays_pre_process_data where `abandon` = '{abandon}' and `content_type`='{content_type}' and `channel_id` in {channel} and `client_id`='{client_id}'"
        if process_phase == 'post' and regulation_type != 'R05':  # 后置规则处理:post
            sql = f"select * from ays_post_process_data_valid where `done` = '{done}' and `content_type`='{content_type}' and `channel_id` in {channel} and `client_id`='{client_id}'"
        if process_phase == 'post' and regulation_type == 'R05':  # process_phase规则阶段、前置处理:pre 后置处理:post
            sql = f"select * from ays_post_process_data_valid where `content_type`='{content_type}' and `channel_id` in {channel} and `client_id`='{client_id}'"

        print("sql::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::", sql)
        processed_data_content = get_data(client_name, 'data_query', sql)

        if detail_type == "0" and process_phase == 'post':  # 满足后置规则条件

            before_processing_raw_id = before_processing_raw_data(client_name, rule_detail)  # 返回后置原始表中满足条件的数据id
            print("444444444444", before_processing_raw_id)
            if processed_data_content:
                for item in processed_data_content:
                    id = item.get('id')  # 每条数据的id
                    hit_rules = item.get('hit_rules')  # 获取每条数据中hit_rules字段的数据内容，hit_rules包含执行规则的所有id
                    if hit_rules is not None and id in before_processing_raw_id:
                        # 使用json.loads()函数将JSON字符串转换为Python字典
                        hit_rules = json.loads(hit_rules)
                        rule_ids = hit_rules["rule_ids"]

                        if rule_id in rule_ids:  # 根据id获取每条数据中所执行规则的所有数据
                            eligible_data.append(item)

        if detail_type == "1" and process_phase == 'post':  # 满足后置规则执行条件
            print('符合条件的！！！！！！！', eligible_data)
            for item in eligible_data:

                field_name_content = item.get(field_name)
                if field_name_content is None:
                    print("field_name_content为空", item.get('id'))
                    continue
                if condition_type == 'value':
                    if logical_operator == 'contain':
                        # 检查字符串是否包含另一个字符串
                        condition = condition_detail in field_name_content
                    elif logical_operator == 'equals':
                        # 检查两个字符串是否相等
                        condition = field_name_content == condition_detail
                    elif logical_operator == 'empty':
                        # 检查字符串是否为空
                        condition = field_name_content == ''
                    elif logical_operator == 'notEmpty':
                        # 检查字符串是否非空
                        condition = field_name_content != ''
                    elif logical_operator == 'notEqual':
                        # 检查两个字符串是否不相等
                        condition = field_name_content != condition_detail
                    elif logical_operator == 'notContain':
                        # 检查字符串是否不包含另一个字符串
                        condition = condition_detail not in field_name_content

                if condition_type == 'resourceGroup':
                    print('[names]', names)
                    if logical_operator == 'contain':
                        # 检查字符串是否包含另一个字符串
                        condition = names in field_name_content
                    elif logical_operator == 'equals':
                        # 检查两个字符串是否相等
                        condition = field_name_content == names
                    elif logical_operator == 'notEqual':
                        # 检查两个字符串是否不相等
                        condition = field_name_content != names
                    elif logical_operator == 'notContain':
                        # 检查字符串是否不包含另一个字符串
                        condition = names not in field_name_content

                if condition_type == 'regex':
                    if logical_operator == 'contain':
                        # 正则表达式检查字符串是否包含另一个字符串
                        condition = re.search(condition_detail, field_name_content)
                    elif logical_operator == 'notEqual':
                        # 检查两个字符串是否不相等
                        condition = not re.search(condition_detail, field_name_content)
                    elif logical_operator == 'notContain':
                        condition = not re.search(condition_detail, field_name_content)
                if condition:
                    print("验证正确！！！！！！！！！！")
                else:
                    failure_processed = False
                    print("验证错误！！！！！！！！！！", item.get('id'))
        # 过滤只有条件没有执行动作，detail_type==0
        if detail_type == "0" and process_phase == 'post' and regulation_type == 'R05':  # 满足规则执行条件，执行后置处理规则过滤
            # print('[processed_data_content]', processed_data_content)
            if processed_data_content:
                for item in processed_data_content:
                    hit_rules = item.get('hit_rules')  # 获取每条数据中hit_rules字段的数据内容，hit_rules包含执行规则的所有id
                    if hit_rules is not None:
                        # 使用json.loads()函数将JSON字符串转换为Python字典
                        hit_rules = json.loads(hit_rules)
                        rule_ids = hit_rules["rule_ids"]  # 获取每条数据中所执行规则的所有id
                        if rule_id in rule_ids:
                            field_name_content = item.get(field_name)
                            if field_name_content is not None:
                                if condition_type == 'value':
                                    if logical_operator == 'contain':
                                        # 检查字符串是否包含另一个字符串
                                        condition = condition_detail in field_name_content
                                    elif logical_operator == 'equals':
                                        # 检查两个字符串是否相等
                                        condition = field_name_content == condition_detail
                                    elif logical_operator == 'empty':
                                        # 检查字符串是否为空
                                        condition = field_name_content == ''
                                    elif logical_operator == 'notEmpty':
                                        # 检查字符串是否非空
                                        condition = field_name_content != ''
                                    elif logical_operator == 'notEqual':
                                        # 检查两个字符串是否不相等
                                        condition = field_name_content != condition_detail
                                    elif logical_operator == 'notContain':
                                        # 检查字符串是否不包含另一个字符串
                                        condition = condition_detail not in field_name_content

                                if condition_type == 'resourceGroup':
                                    print('[names]', names)
                                    if logical_operator == 'contain':
                                        # 检查字符串是否包含另一个字符串
                                        condition = names in field_name_content
                                    elif logical_operator == 'equals':
                                        # 检查两个字符串是否相等
                                        condition = field_name_content == names
                                    elif logical_operator == 'notEqual':
                                        # 检查两个字符串是否不相等
                                        condition = field_name_content != names
                                    elif logical_operator == 'notContain':
                                        # 检查字符串是否不包含另一个字符串
                                        condition = names not in field_name_content

                                if condition_type == 'regex':
                                    if logical_operator == 'contain':
                                        # 正则表达式检查字符串是否包含另一个字符串
                                        condition = re.search(condition_detail, field_name_content)
                                    elif logical_operator == 'notEqual':
                                        # 检查两个字符串是否不相等
                                        condition = not re.search(condition_detail, field_name_content)
                                    elif logical_operator == 'notContain':
                                        condition = not re.search(condition_detail, field_name_content)
                                if condition:
                                    print(f"{field_name}字段的值为", field_name_content)
                                    print("包含内容符合条件数据id为", item.get('id'))
                                    new_id_array.append(item.get('id'))
                                else:
                                    failure_processed = False
                                    print("不符合条件数据id为", item.get('id'))
                failure_raw = post_raw_data(client_name, logical_operator, condition_detail, field_name, new_id_array,
                                            content_type, channel)
            else:
                print("后置规则过滤没有查询到数据")

        # 过滤只有条件没有执行动作，detail_type==0
        if detail_type == "0" and process_phase == 'pre' and regulation_type == 'R05':  # 满足规则执行条件，执行前置处理规则过滤
            # print('[processed_data_content]', processed_data_content)
            if processed_data_content:
                for item in processed_data_content:
                    hit_rules = item.get('hit_rules')  # 获取每条数据中hit_rules字段的数据内容，hit_rules包含执行规则的所有id
                    if hit_rules is not None:
                        # 使用json.loads()函数将JSON字符串转换为Python字典
                        hit_rules = json.loads(hit_rules)
                        rule_ids = hit_rules["rule_ids"]  # 获取每条数据中所执行规则的所有id
                        if rule_id in rule_ids:
                            data_content = item.get('data')  # 获取每条数据中data字段的数据内容
                            if data_content is not None:
                                # 使用json.loads()函数将JSON字符串转换为Python字典
                                data_content = json.loads(data_content)
                                field_name_content = data_content.get(field_name)  # 获取每条数据中data字段中field_name字段的值
                                if field_name_content is None:
                                    print("field_name_content为空", item.get('new_id'))
                                    continue
                                if condition_type == 'value':
                                    if logical_operator == 'contain':
                                        # 检查字符串是否包含另一个字符串
                                        condition = condition_detail in field_name_content
                                    elif logical_operator == 'equals':
                                        # 检查两个字符串是否相等
                                        condition = field_name_content == condition_detail
                                    elif logical_operator == 'empty':
                                        # 检查字符串是否为空
                                        condition = field_name_content == ''
                                    elif logical_operator == 'notEmpty':
                                        # 检查字符串是否非空
                                        condition = field_name_content != ''
                                    elif logical_operator == 'notEqual':
                                        # 检查两个字符串是否不相等
                                        condition = field_name_content != condition_detail
                                    elif logical_operator == 'notContain':
                                        # 检查字符串是否不包含另一个字符串
                                        condition = condition_detail not in field_name_content

                                if condition_type == 'resourceGroup':
                                    print('[names]', names)
                                    if logical_operator == 'contain':
                                        # 检查字符串是否包含另一个字符串
                                        condition = names in field_name_content
                                    elif logical_operator == 'equals':
                                        # 检查两个字符串是否相等
                                        condition = field_name_content == names
                                    elif logical_operator == 'notEqual':
                                        # 检查两个字符串是否不相等
                                        condition = field_name_content != names
                                    elif logical_operator == 'notContain':
                                        # 检查字符串是否不包含另一个字符串
                                        condition = names not in field_name_content

                                if condition_type == 'regex':
                                    if logical_operator == 'contain':
                                        # 正则表达式检查字符串是否包含另一个字符串
                                        condition = re.search(condition_detail, field_name_content)
                                    elif logical_operator == 'notEqual':
                                        # 检查两个字符串是否不相等
                                        condition = not re.search(condition_detail, field_name_content)
                                    elif logical_operator == 'notContain':
                                        condition = not re.search(condition_detail, field_name_content)
                                if condition:
                                    print(f"{field_name}字段的值为", field_name_content)
                                    print("包含内容符合条件数据id为", item.get('new_id'))
                                    new_id_array.append(item.get('new_id'))
                                else:
                                    failure_processed = False
                                    print("不符合条件数据id为", item.get('new_id'))
                failure_raw = raw_data(client_name, logical_operator, condition_detail, field_name, new_id_array,
                                       content_type, channel)
            else:
                print("前置规则过滤没有查询到数据")
        assert failure_processed and failure_raw
